﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.Windows;

namespace KgUtils.Wpf.Converters
{
    [ValueConversion(typeof(decimal?), typeof(string))]
    public class AmountConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var sourceValue = (decimal?)value;
            var format = (parameter == null) ? "{0}" : (string)parameter;
            return (!sourceValue.HasValue) ? null : String.Format(culture.NumberFormat, format, sourceValue);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            decimal targetValue;
            string sourceValue = (string)value;
            if (sourceValue != null)
                sourceValue = sourceValue.Replace('.', ',');

            if (String.IsNullOrWhiteSpace(sourceValue))
                return null;
            else if (Decimal.TryParse(sourceValue, NumberStyles.Number, culture.NumberFormat, out targetValue))
                return targetValue;
            else
                return DependencyProperty.UnsetValue;
            //return value; // error parsing : returns the source value and let the framework handle the problem.
        }

        #endregion
    }
}
